//
//  YahooSearchPlugin.m
//  YahooSearchPlugin
//
//  Created by Jeremy Johnstone on 12/26/07.
//  Copyright 2007 Jeremy Johnstone. All rights reserved.
//

/*
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

#import "YahooSearchPlugin.h"
#import "GoogleSearchChannel.h"
#import "BrowserWindowController.h"


/* Code for doing method swizzling. Borrowed from ForgetMeNot / SIMBL homepage */

typedef struct objc_method *Method;

struct objc_method {
  SEL method_name;
  char *method_types;
  IMP method_imp;
};

/**
 * Renames the selector for a given method.
 * Searches for a method with _oldSelector and reassigned _newSelector to that
 * implementation.
 * @return NO on an error and the methods were not swizzled
 */
BOOL JJRenameSelector(Class _class, SEL _oldSelector, SEL _newSelector)
{
        Method method = nil;

        // First, look for the methods
        method = (Method)class_getInstanceMethod(_class, _oldSelector);
        if (method == nil)
                return NO;

        method->method_name = _newSelector;
        return YES;
}

@implementation YahooSearchPlugin

/**
 * A special method called by SIMBL once the application has started and all classes are initialized.
 */
+ (void) load
{
        //YahooSearchPlugin* plugin = [YahooSearchPlugin sharedInstance];
        
		// Exchange Safari's idea of a search engine with ours
		JJRenameSelector([GoogleSearchChannel class], @selector(URLWithSearchCriteria:), @selector (_safari_URLWithSearchCriteria:));
		JJRenameSelector([GoogleSearchChannel class], @selector(_jj_URLWithSearchCriteria:), @selector(URLWithSearchCriteria:));
		JJRenameSelector([BrowserWindowController class], @selector(_setUpSearchField), @selector (_safari_setUpSearchField));
		JJRenameSelector([BrowserWindowController class], @selector(_jj_setUpSearchField), @selector(_setUpSearchField));
		
		NSLog(@"YahooSearchPlugin installed");
}

/**
 * @return the single static instance of the plugin object
 */
+ (YahooSearchPlugin*) sharedInstance
{
        static YahooSearchPlugin* plugin = nil;

        if (plugin == nil)
                plugin = [[YahooSearchPlugin alloc] init];

        return plugin;
}

@end
